package com.jeff.utils;

import android.annotation.SuppressLint;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PinYinUtil {

    public static String getFullPYString(String name) {
        String py = "";
        char[] chars = name.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            //过滤数字、字母，不翻译为拼音
            if (c <= 128) {
                py += (c + "").toLowerCase();
            } else {

                String[] pinyingStr = PinyinHelper.toHanyuPinyinStringArray(chars[i]);
                if (pinyingStr == null) {
                    return " ";
                }
                for (int j = 0; j < pinyingStr.length; j++) {
                    py += pinyingStr[0].toUpperCase();
                }
            }
        }
        Pattern pattern = Pattern.compile("[\\d]");
        Matcher matcher = pattern.matcher(py);
        py = matcher.replaceAll("").trim();

        return py;
    }

    public static char[] getHeadByChar(String name) {
        return getHeadByChar(name, true);
    }

    /**
     * 取汉字的首字母
     *
     * @param name
     * @param isCapital 是否是大写
     * @return
     */
    @SuppressLint("DefaultLocale")
    public static char[] getHeadByChar(String name, boolean isCapital) {
        // 如果不是汉字直接返回
        if (name == null || name.length() <= 0) {
            return null;
        }
        char src = name.charAt(0);
        if (src <= 128) {
            if ((src >= 97 && src <= 122)
                    || (src >= 65 && src <= 90)) {
                String s = String.valueOf(src);
                return s.toCharArray();
            }

            return new char[]{'★'};
        }
        char[] headChars = new char[1];
        try {
            // 获取所有的拼音
            String[] pinyingStr = PinyinHelper.toHanyuPinyinStringArray(src);
            // 过滤中文符号
            if (pinyingStr == null) {
                return new char[]{'★'};
            }

            int i = 0;

            char headChar = pinyingStr[0].charAt(0);
            // 首字母是否大写，默认是小写
            if (isCapital) {
                headChars[i] = Character.toUpperCase(headChar);
            } else {
                headChars[i] = headChar;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return headChars;
    }
}
